/*
	Copyright (c) 2009, M.P. Bartnig & A. Gosman
	
	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:
	
	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.
	
	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/
package nl.sanity.ui
{
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.events.Event;
	import flash.events.FocusEvent;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.filters.GlowFilter;
	import flash.ui.Keyboard;
	
	import nl.sanity.debug.LogConsole;
	import nl.sanity.managers.AlignmentManager;
	import nl.sanity.ui.helpers.DisplayState;
	import nl.sanity.ui.helpers.LabelStyle;
	import nl.sanity.ui.helpers.UIAlign;
	
	/**
	 * Button
	 *
	 * @langversion ActionScript 3
	 *
	 * @author M.P. Bartnig
	 * @since  16/03/2009
	 */
	public class Button extends BaseComponent
	{
		public static const	DEFAULT_WIDTH		:Number		= 100;
		public static const	DEFAULT_HEIGHT		:Number		= 50;
		public static const	DEFAULT_BUTTONMODE	:Boolean	= true;
		public static const	DEFAULT_HANDCURSOR	:Boolean	= true;
		
		protected var _labelText				:String;
		protected var _labelAlign				:UIAlign;
		protected var _labelStyle				:LabelStyle;
		protected var _textLabel				:Label;
		protected var _selected					:Boolean;
		protected var _toggle					:Boolean;
		protected var _up						:Boolean;
		protected var _over						:Boolean;
		protected var _down						:Boolean;
		protected var _data						:Object;
		

		
		// --- CONSTRUCTOR ----------------------------------------

		public function Button( parent:DisplayObjectContainer = null, posX:Number = 0, posY:Number = 0, scalable:Boolean = true, verbose:Boolean = false )
		{
			super( parent, posX, posY, scalable, verbose );
		}
		
		// --- OVERRIDE FUNCTIONS ----------------------------------------
		
		override protected function init():void
		{
			super.init();
			
			_defaultState	= DisplayState.UP;
			_currentState	= _defaultState;
			_enabled		= true;
			
			buttonMode		= Button.DEFAULT_BUTTONMODE;
			useHandCursor	= Button.DEFAULT_HANDCURSOR;
			
			setRequiredStates();
		}
		
		override protected function setRequiredStates():void
		{
				_requiredStates	= [	DisplayState.UP,
									DisplayState.OVER,
									DisplayState.DOWN,
									DisplayState.DISABLED ];
		}
		
		override public function draw():void
		{
			if( _verbose ) LogConsole.log( "Button.draw" );
			
			if (  numStates() > 0 )
			{
				updateDisplayState();
			}
			
			if ( _textLabel )
			{
				updateLabel();
			}
			
			super.draw();
		}
		
		override protected function addChildren():void
		{
			// Create default layout if it hasn't been set thru the setter
			if ( !_labelAlign )
			{
				_labelAlign = new UIAlign();
			}
		}
		
		override protected function addEventListeners():void
		{
			super.addEventListeners();
			
			addEventListener( MouseEvent.ROLL_OVER, onMouseOver, false, 0, true );
			addEventListener( MouseEvent.MOUSE_DOWN, onMouseDown, false, 0, true );
			
		}
		
		override protected function removeEventListeners():void
		{
			super.removeEventListeners();
			
			removeEventListener( MouseEvent.ROLL_OVER, onMouseOver );
			removeEventListener( MouseEvent.MOUSE_DOWN, onMouseDown );
		}
		
		override protected function onFocusIn( event:FocusEvent ):void
		{
			super.onFocusIn( event );
			
			setKeySelection();
			updateFocusRect( [ new GlowFilter( 0xB5D5FF ) ] );
		}
		
		override protected function onFocusOut( event:FocusEvent ):void
		{
			super.onFocusOut( event );
			
			setKeySelection();
			updateFocusRect();
		}
		
		
		// --- PROTECTED FUNCTIONS ----------------------------------------
		
		protected function removeCurrentDisplayState():void
		{
			if( _verbose ) LogConsole.log( "Button.removeCurrentDisplayState" );
			
			if ( _currentDisplayState && contains( _currentDisplayState ) )
			{
				removeChild( _currentDisplayState );
				_currentDisplayState 	= null;
			}
		}
		
		protected function addTextLabel():void
		{
			_textLabel				= new Label( this, _labelText );
			addChild( _textLabel );
		}
		
		protected function updateLabel( event:Event = null ):void
		{
			_textLabel.alignment	= _labelAlign;
			_textLabel.styleSheet 	= _labelStyle;
			_textLabel.applyStyle( _currentState );
			AlignmentManager.align( _textLabel );
		}
		
		protected function onMouseOver( event:MouseEvent = null ):void
		{
			_over			= true;
			_currentState	= _selected ? DisplayState.SELECTED_OVER : DisplayState.OVER;
			
			addEventListener( MouseEvent.ROLL_OUT, onMouseOut, false, 0, true );
			
			draw();
		}
		
		protected function onMouseOut( event:MouseEvent ):void
		{
			_over			= false;
			_currentState	= _selected ? DisplayState.SELECTED_UP : DisplayState.UP;
			
			removeEventListener( MouseEvent.ROLL_OUT, onMouseOut );
			
			draw();
		}
		
		protected function onMouseDown( event:MouseEvent = null ):void
		{
			_down = true;
			
			_currentState	= _selected ? DisplayState.SELECTED_DOWN : DisplayState.DOWN;
			
			removeEventListener( MouseEvent.ROLL_OUT, onMouseOut );
			
			stage.addEventListener( MouseEvent.MOUSE_UP, onMouseUp, false, 0, true );
			stage.addEventListener( Event.MOUSE_LEAVE, onStageMouseLeave, false, 0, true );
			
			draw();
		}
		
		protected function onMouseUp( event:MouseEvent = null ):void
		{
			stage.removeEventListener( MouseEvent.MOUSE_UP, onMouseUp );
			
			if ( _toggle && _over )
			{
				_selected = !_selected;
			}
			
			_currentState = _selected ? DisplayState.SELECTED_UP : DisplayState.UP;
			
			_down = _selected;
			
			draw();
		}
		
		protected function onStageMouseLeave( event:Event ):void
		{
			stage.removeEventListener( Event.MOUSE_LEAVE, onStageMouseLeave );
			onMouseUp();
		}
		
		protected function setKeySelection():void
		{
			if ( _hasFocus )
			{
				addEventListener( KeyboardEvent.KEY_DOWN, onKeyDown, false, 0, true );
				
			}
			else
			{
				if ( hasEventListener( KeyboardEvent.KEY_DOWN ) )
				{
					removeEventListener( KeyboardEvent.KEY_DOWN, onKeyDown );
				}
			}
		}
		
		protected function onKeyDown( event:KeyboardEvent ):void
		{
			if ( event.keyCode == Keyboard.SPACE || event.keyCode == Keyboard.ENTER )
			{
				removeEventListener( KeyboardEvent.KEY_DOWN, onKeyDown );
				addEventListener( KeyboardEvent.KEY_UP, onKeyUp, false, 0, true );
				
				// Emulate mouse events
				onMouseOver();
				onMouseDown();
			}
			
			event.stopPropagation();
		}
		
		protected function onKeyUp( event:KeyboardEvent ):void
		{
			removeEventListener( KeyboardEvent.KEY_UP, onKeyUp );
			onMouseUp();
			
			setKeySelection();
		}
		
		// --- GETTER/SETTER ----------------------------------------

		override public function set enabled( value:Boolean ):void
		{
			if ( value )
			{
				_currentState	= _selected ? DisplayState.SELECTED_DOWN : DisplayState.UP;
			}
			else
			{
				_currentState	= _selected ? DisplayState.SELECTED_DISABLED : DisplayState.DISABLED;
			}
			
			super.enabled		= value;
		}
		
		public function get data():Object
		{
			return _data;
		}
		public function set data( value:Object ):void
		{
			_data 	= value;
		}

		public function get selected():Boolean
		{
			return _selected;
		}
		public function set selected( value:Boolean ):void
		{
			if ( !_toggle ) return;
			
			_selected		= value;
			_down			= _selected;
			
			_currentState	= _selected ? DisplayState.SELECTED_UP : DisplayState.UP;
			
			draw();
		}
		
		public function get label():String
		{
			return _labelText;
		}
		public function set label( value:String ):void
		{
			_labelText	= value;
			
			if ( !_textLabel )
			{
				addTextLabel();
			}
			else
			{
				_textLabel.text = _labelText;
				
			}
			invalidate();
		}
		
		public function get textLabel():Label
		{
			return _textLabel;
		}
		
		public function get labelStyle():LabelStyle
		{
			return _labelStyle;
		}
		public function set labelStyle( value:LabelStyle ):void
		{
			_labelStyle 		= value;
			invalidate();
		}
		
		public function get labelAlign():UIAlign
		{
			return _labelAlign;
		}
		public function set labelAlign( value:UIAlign ):void
		{
			_labelAlign	= value;
			invalidate();
		}
		
		public function get currentDisplayState():DisplayObject
		{
			return _currentDisplayState;
		}

	}
}